<div class="box">
    
  <div class="box-header">

    <div class="row">
        <div class="col-sm-5">
            <ob_link><a class="btn btn-primary btn-sm" href="{:url('productAdd')}"><i class="fa fa-plus"></i> 新增</a></ob_link>
            <!-- <ob_link><a class="btn btn-success btn-sm" href="{:url('productImport')}"><i class="fa fa-upload"></i> 批量导入</a></ob_link> -->
        </div>
        
        <div class="col-sm-7">
            <div class="box-tools search-form pull-right">
                <div class="input-group input-group-sm">
                    
                    <input type="text" name="search_data" style="width: 200px;" class="form-control pull-right" value="{:input('search_data')}" placeholder="支持产品名称|分类|品牌">

                    <div class="input-group-btn">
                      <button type="button" id="search"  url="{:url('index')}" class="btn btn-info btn-flat"><i class="fa fa-search"></i></button>
                    </div>

                </div>
           </div>
        </div>
    </div>
    
  </div>
    
    
  <div class="box-body table-responsive">
    <table  class="table table-bordered table-hover table-striped">
      <thead>
      <tr>
          <th><input type="checkbox" id="checkAll" /></th>
          <th>ID</th>
          <th>产品图片</th>
          <th>产品名称</th>
          <th>分类</th>
          <th>价格信息</th>
          <!-- <th>库存</th> -->
          <th class="sort-th">排序</th>
          <th>状态</th>
          <!-- <th>创建时间</th> -->
          <th>操作</th>
      </tr>
      </thead>
      
      {notempty name='list'}
        <tbody>
            {volist name='list' id='vo'}
                <tr id="product-row-{$vo.id}">
                  <td><input type="checkbox" class="product-checkbox" value="{$vo.id}" /></td>
                  <td>{$vo.id}</td>
                  <td>
                      <img style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;" src="{$vo.cover_image|default='/static/images/default_product.png'}"/>
                  </td>
                  <td>{$vo.name}</td>
                  <td>{$vo.category_text}</td>
                  <td class="price-cell">
                      <div class="price-info">
                          <div class="current-price">
                              <span class="price-label">当前：</span>
                              <span class="price-value editable-price" data-id="{$vo.id}" data-original="{$vo.market_price}">¥{$vo.market_price}</span>
                              <i class="fa fa-edit price-edit-icon" title="点击编辑价格"></i>
                          </div>
                          <div class="price-change">
                              <span class="yesterday-price">昨日：¥{$vo.yesterday_price|default='0.00'}</span>
                              {notempty name="vo.change_rate"}
                                  {gt name="vo.change_rate" value="0"}
                                      <span class="price-up">↗ +{$vo.change_rate}%</span>
                                  {else/}
                                      <span class="price-down">↘ {$vo.change_rate}%</span>
                                  {/gt}
                              {else/}
                                  <span class="price-stable">— 0%</span>
                              {/notempty}
                          </div>
                      </div>
                  </td>
                  <!-- <td>{$vo.stock}</td> -->
                  <td><input type="text" class="sort-th sort-text" href="{:url('setSort')}" id="{$vo.id}" value="{$vo.sort}" /></td>
                  <td>
                      {if condition="$vo.product_status eq 1"}
                          <span class="label label-success">上架</span>
                      {else/}
                          <span class="label label-danger">下架</span>
                      {/if}
                  </td>
                  <!-- <td>{$vo.create_time}</td> -->
                  <td class="text-center">
                      <ob_link><a href="{:url('productEdit', array('id' => $vo['id']))}"><span class='badge bg-green'>编 辑</span></a></ob_link>
                      &nbsp;
                      <ob_link><a href="{:url('productEdit', array('id' => $vo.id))}" onclick="event.preventDefault(); openPriceModal({$vo.id}, '{$vo.name}');" class="badge bg-purple">价格详情</a></ob_link>
                      &nbsp;
                      {if condition="$vo.product_status eq 1"}
                          <ob_link><a class="confirm ajax-get" href="{:url('productStatus', array('id' => $vo['id'], 'status' => 0))}"><span class='badge bg-orange'>下 架</span></a></ob_link>
                      {else/}
                          <ob_link><a class="confirm ajax-get" href="{:url('productStatus', array('id' => $vo['id'], 'status' => 1))}"><span class='badge bg-blue'>上 架</span></a></ob_link>
                      {/if}
                      &nbsp;
                      <ob_link><a class="confirm ajax-get"  href="{:url('productDel', array('id' => $vo['id']))}"><span class='badge bg-red'>删 除</span></a></ob_link>
                  </td>
                </tr>
            {/volist}
        </tbody>
        {else/}
        <tbody><tr class="odd"><td colspan="9" class="text-center" valign="top">{:e(config_value('empty_list_describe', 'Oh! 暂时还没有数据~'))}</td></tr></tbody>
      {/notempty}
    </table>
  </div>

  <div class="box-footer clearfix text-center">
      {$list->render()|raw}
  </div>

</div>

<!-- 价格管理弹窗 -->
<div class="modal fade" id="priceModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">价格详情管理 - <span id="productName"></span></h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <!-- 左侧：价格编辑和历史选择 -->
                    <div class="col-md-4">
                        <div class="panel panel-primary">
                            <div class="panel-heading">当日价格编辑</div>
                            <div class="panel-body">
                                <div class="form-group">
                                    <label>当前价格</label>
                                    <div class="input-group">
                                        <span class="input-group-addon">¥</span>
                                        <input type="number" class="form-control" id="currentPrice" step="0.01">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>价格日期</label>
                                    <input type="date" class="form-control" id="priceDate">
                                </div>
                                <div class="form-group">
                                    <label>变动原因</label>
                                    <select class="form-control" id="changeReason">
                                        <option value="">请选择</option>
                                        <option value="market">市场调整</option>
                                        <option value="cost">成本变化</option>
                                        <option value="promotion">促销活动</option>
                                        <option value="competition">竞争调整</option>
                                        <option value="other">其他原因</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>备注</label>
                                    <textarea class="form-control" id="priceRemark" rows="3" placeholder="详细说明价格变动原因..."></textarea>
                                </div>
                                <div class="form-group">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" id="onlyHistory" checked> 仅修改历史价格，当前价格不变
                                        </label>
                                        <small class="help-block">勾选后，如果价格日期不是今天，将只记录历史价格而不改变商品当前价格</small>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-primary btn-block" onclick="savePriceChange()">
                                    <i class="fa fa-save"></i> 保存价格变动
                                </button>
                            </div>
                        </div>
                        
                        <!-- 历史价格快速选择 -->
                        <div class="panel panel-info">
                            <div class="panel-heading">历史价格快速选择</div>
                            <div class="panel-body">
                                <div id="quickPriceSelect" style="display: flex;">
                                    <!-- 动态加载最近的价格选项 -->
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 右侧：价格趋势图和统计 -->
                    <div class="col-md-8">
                        <div class="panel panel-success">
                            <div class="panel-heading">
                                价格趋势分析
                                <div class="pull-right">
                                    <button class="btn btn-xs btn-default" onclick="changePeriod('7d')">7天</button>
                                    <button class="btn btn-xs btn-default" onclick="changePeriod('30d')">30天</button>
                                    <button class="btn btn-xs btn-default" onclick="changePeriod('90d')">90天</button>
                                </div>
                            </div>
                            <div class="panel-body">
                                <canvas id="priceChart" width="600" height="300"></canvas>
                            </div>
                        </div>
                        
                        <!-- 价格统计信息 -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="info-box bg-aqua">
                                    <span class="info-box-icon"><i class="fa fa-arrow-up"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">最高价</span>
                                        <span class="info-box-number" id="maxPrice">¥0.00</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="info-box bg-red">
                                    <span class="info-box-icon"><i class="fa fa-arrow-down"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">最低价</span>
                                        <span class="info-box-number" id="minPrice">¥0.00</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="info-box bg-green">
                                    <span class="info-box-icon"><i class="fa fa-calculator"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">平均价</span>
                                        <span class="info-box-number" id="avgPrice">¥0.00</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="info-box bg-yellow">
                                    <span class="info-box-icon"><i class="fa fa-exchange"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">变动次数</span>
                                        <span class="info-box-number" id="changeCount">0</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 底部：最近价格变动记录 -->
                <div class="row" style="margin-top: 20px;">
                    <div class="col-md-12">
                        <div class="panel panel-warning">
                            <div class="panel-heading">
                                最近价格变动记录
                                <div class="pull-right">
                                    <button class="btn btn-xs btn-warning" onclick="exportPriceHistory()">
                                        <i class="fa fa-download"></i> 导出记录
                                    </button>
                                </div>
                            </div>
                            <div class="panel-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover" id="priceHistoryTable">
                                        <thead>
                                            <tr>
                                                <th>变动时间</th>
                                                <th>原价格</th>
                                                <th>新价格</th>
                                                <th>变动幅度</th>
                                                <th>变动原因</th>
                                                <th>备注</th>
                                                <th>操作人</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- 动态加载 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<style>
/* 价格信息样式 */
.price-cell {
    min-width: 150px;
}

.price-info {
    font-size: 12px;
}

.current-price {
    margin-bottom: 5px;
    font-weight: bold;
}

.price-label {
    color: #666;
    font-size: 11px;
}

.price-value {
    color: #333;
    font-size: 14px;
    cursor: pointer;
}

.price-edit-icon {
    margin-left: 5px;
    color: #3c8dbc;
    /* cursor: pointer; */
    opacity: 0.7;
}

.price-edit-icon:hover {
    opacity: 1;
}

.price-change {
    font-size: 11px;
}

.yesterday-price {
    color: #999;
    margin-right: 10px;
}

/* 价格编辑按钮样式 */
.price-edit-buttons {
    margin-left: 5px;
    display: inline-block;
}

.price-confirm-btn, .price-cancel-btn {
    margin-left: 2px;
    padding: 2px 6px;
    font-size: 11px;
    line-height: 1.2;
}

.price-editing {
    width: 80px;
    padding: 2px 5px;
    font-size: 12px;
    border: 1px solid #ddd;
    border-radius: 3px;
}

.price-up {
    color: #d73925;
    font-weight: bold;
}

.price-down {
    color: #00a65a;
    font-weight: bold;
}

.price-stable {
    color: #999;
}

/* 价格趋势展开行样式 */
.price-detail-row {
    background-color: #f9f9f9;
}

.price-trend-container {
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 5px;
    background-color: white;
}

.price-stats h5 {
    margin-top: 0;
    color: #3c8dbc;
}

.price-stats p {
    margin-bottom: 8px;
    font-size: 13px;
}

/* 内联编辑样式 */
.price-editing {
    background-color: #fff3cd;
    border: 1px solid #ffeaa7;
    border-radius: 3px;
    padding: 2px 5px;
    width: 80px;
    font-size: 12px;
}

/* 批量操作工具栏 */
#batch-tools {
    margin-left: 10px;
}

/* 复选框样式 */
.product-checkbox {
    transform: scale(1.2);
}

/* 模态框样式调整 */
.modal-xl {
    width: 95%;
    max-width: 1200px;
}

/* 快速价格选择按钮 */
.quick-price-btn {
    display: block;
    /* width: 100%; */
    margin-bottom: 5px;
    text-align: left;
    font-size: 12px;
    padding: 5px 10px;
}

/* 信息框样式 */
.info-box {
    margin-bottom: 10px;
}

.info-box-number {
    font-size: 16px !important;
}

/* 价格预览表格 */
.table-sm th,
.table-sm td {
    padding: 5px;
    font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .price-info {
        font-size: 11px;
    }
    
    .current-price {
        margin-bottom: 3px;
    }
    
    .price-value {
        font-size: 12px;
    }
    
    .modal-xl {
        width: 98%;
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
/**
 * 产品价格管理系统
 * @author 王勇程 <laughskydragon@qq.com>
 */

// 全局变量
let currentProductId = 0;
let priceChart = null;
let miniCharts = {};
let selectedProducts = [];

// 页面初始化
$(document).ready(function() {
    initEventHandlers();
    updateBatchToolsVisibility();
});

// 初始化事件处理器
function initEventHandlers() {
    // 全选复选框
    $('#checkAll').change(function() {
        $('.product-checkbox').prop('checked', this.checked);
        updateSelectedProducts();
    });
    
    // 产品复选框
    $(document).on('change', '.product-checkbox', function() {
        updateSelectedProducts();
        updateCheckAllStatus();
    });
    
    // 价格内联编辑
    $(document).on('click', '.editable-price', function() {
        startPriceEdit(this);
    });
    
    // 批量调价类型变化
    $('#adjustType').change(function() {
        updateAdjustValueUI();
        updatePricePreview();
    });
    
    // 调价值变化
    $('#adjustValue').on('input', function() {
        updatePricePreview();
    });
    
    // 价格预警类型变化
    $('#alertHighPrice, #alertLowPrice, #alertPriceChange').change(function() {
        updateAlertGroups();
    });
}

// 更新选中的产品
function updateSelectedProducts() {
    selectedProducts = [];
    $('.product-checkbox:checked').each(function() {
        const productId = $(this).val();
        const row = $(this).closest('tr');
        const name = row.find('td:nth-child(3)').text();
        const price = parseFloat(row.find('.price-value').data('original'));
        
        selectedProducts.push({
            id: productId,
            name: name,
            price: price
        });
    });
    
    updateBatchToolsVisibility();
    $('#selectedCount').text(selectedProducts.length);
}

// 更新全选状态
function updateCheckAllStatus() {
    const total = $('.product-checkbox').length;
    const checked = $('.product-checkbox:checked').length;
    
    $('#checkAll').prop('indeterminate', checked > 0 && checked < total);
    $('#checkAll').prop('checked', checked === total);
}

// 格式化价格显示，整数不显示小数点
function formatPrice(price) {
    const num = parseFloat(price);
    if (isNaN(num)) return '0';
    
    // 如果是整数，不显示小数点
    if (num % 1 === 0) {
        return num.toString();
    }
    
    // 如果有小数，显示两位小数
    return num.toFixed(2);
}

// 更新批量工具栏显示
function updateBatchToolsVisibility() {
    if (selectedProducts.length > 0) {
        $('#batch-tools').show();
    } else {
        $('#batch-tools').hide();
    }
}

// 开始价格内联编辑
function startPriceEdit(element) {
    const $element = $(element);
    const currentPrice = $element.data('original');
    const productId = $element.data('id');
    
    // 如果价格为0，显示空值让用户输入新价格
    const displayValue = (currentPrice == 0) ? '' : currentPrice;
    
    const input = $('<input>')
        .addClass('price-editing')
        .attr('type', 'number')
        .attr('step', '0.01')
        .attr('placeholder', '请输入价格')
        .val(displayValue)
        .on('keyup', function(e) {
            if (e.which === 27) { // ESC键
                cancelPriceEdit($element, currentPrice);
            }
        });
    
    // 创建确认和取消按钮
    const confirmBtn = $('<button>')
        .addClass('btn btn-xs btn-success price-confirm-btn')
        .html('<i class="fa fa-check"></i>')
        .attr('title', '确认修改')
        .on('click', function() {
            finishPriceEdit(input[0], $element, productId);
        });
    
    const cancelBtn = $('<button>')
        .addClass('btn btn-xs btn-default price-cancel-btn')
        .html('<i class="fa fa-times"></i>')
        .attr('title', '取消修改')
        .on('click', function() {
            cancelPriceEdit($element, currentPrice);
        });
    
    // 创建按钮容器
    const buttonContainer = $('<span>').addClass('price-edit-buttons').append(confirmBtn).append(cancelBtn);
    
    $element.hide().after(buttonContainer).after(input);
    input.focus().select();
}

// 完成价格编辑
function finishPriceEdit(input, $originalElement, productId) {
    const newPrice = parseFloat($(input).val());
    const originalPrice = $originalElement.data('original');
    
    if (isNaN(newPrice) || newPrice <= 0) {
        toast.warning('请输入有效的价格');
        $(input).focus();
        return;
    }
    
    if (newPrice === originalPrice) {
        cancelPriceEdit($originalElement, originalPrice);
        return;
    }
    
    // 保存价格变动
    saveQuickPriceChange(productId, newPrice, function(success) {
        if (success) {
            $originalElement.text('¥' + formatPrice(newPrice)).data('original', newPrice).show();
            $(input).remove();
            $originalElement.siblings('.price-edit-buttons').remove();
            // 更新价格变动显示
            updatePriceChangeDisplay(productId, originalPrice, newPrice);
        } else {
            $(input).focus();
        }
    });
}

// 取消价格编辑
function cancelPriceEdit($originalElement, originalPrice) {
    $originalElement.siblings('.price-editing').remove();
    $originalElement.siblings('.price-edit-buttons').remove();
    $originalElement.show().text('¥' + formatPrice(originalPrice));
}

// 快速保存价格变动
function saveQuickPriceChange(productId, newPrice, callback) {
    $.ajax({
        url: '{:url("price/change")}',
        type: 'POST',
        data: {
            product_id: productId,
            price: newPrice,
            price_date: new Date().toISOString().split('T')[0],
            remark: '快速调价'
        },
        dataType: 'json',
        success: function(response) {
            // OneBase返回格式：['success', '消息'] 或 ['error', '消息']
            if (response[0] === 'success') {
                callback(true);
            } else {
                toast.error(response[1] || '保存失败');
                callback(false);
            }
        },
        error: function() {
            toast.error('网络错误，请重试');
            callback(false);
        }
    });
}

// 更新价格变动显示
function updatePriceChangeDisplay(productId, oldPrice, newPrice) {
    const change = ((newPrice - oldPrice) / oldPrice * 100).toFixed(2);
    const $row = $('#product-row-' + productId);
    const $changeElement = $row.find('.price-change span:last-child');
    
    if (change > 0) {
        $changeElement.removeClass('price-down price-stable').addClass('price-up').text('↗ +' + change + '%');
    } else if (change < 0) {
        $changeElement.removeClass('price-up price-stable').addClass('price-down').text('↘ ' + change + '%');
    } else {
        $changeElement.removeClass('price-up price-down').addClass('price-stable').text('— 0%');
    }
}

// 更新价格统计
function updatePriceStats(productId, data) {
    const prices = data.map(item => parseFloat(item.price));
    const maxPrice = Math.max(...prices);
    const minPrice = Math.min(...prices);
    const avgPrice = prices.reduce((a, b) => a + b, 0) / prices.length;
    const changeCount = data.length - 1;
    
    $('#max-price-' + productId).text(maxPrice.toFixed(2));
    $('#min-price-' + productId).text(minPrice.toFixed(2));
    $('#avg-price-' + productId).text(avgPrice.toFixed(2));
    $('#change-count-' + productId).text(changeCount);
}

// 打开价格详情弹窗
function openPriceModal(productId, productName) {
    currentProductId = productId;
    $('#productName').text(productName);
    
    // 设置当前日期
    const today = new Date().toISOString().split('T')[0];
    $('#priceDate').val(today);
    
    // 加载数据
    loadPriceInfo(productId);
    loadPriceHistory(productId);
    loadPriceTrend(productId);
    loadQuickPriceSelect(productId);
    
    $('#priceModal').modal('show');
}

// 加载价格信息
function loadPriceInfo(productId) {
    $.ajax({
        url: '{:url("price/getPriceInfo")}',
        type: 'POST',
        data: { product_id: productId },
        dataType: 'json',
        success: function(response) {
            // OneBase返回格式：['success', '消息', data] 或 ['error', '消息']
            if (response[0] === 'success' && response[2]) {
                $('#currentPrice').val(response[2].current_price || response[2].market_price || 0);
            }
        }
    });
}

// 加载价格历史（用于后台管理查看变动记录）
    function loadPriceHistory(productId) {
        $.ajax({
            url: '{:url("price/changeRecords")}',
            type: 'POST',
            data: { product_id: productId, limit: 20 },
            dataType: 'json',
            success: function(response) {
                console.log('价格历史数据:', response); // 调试日志
                // OneBase返回格式：['success', '消息', data] 或 ['error', '消息']
                if (response[0] === 'success' && response[2] && response[2].data && Array.isArray(response[2].data)) {
                    // 处理分页格式的数据
                    const historyData = response[2].data;
                    let html = '';
                    historyData.forEach(function(item) {
                        const changeClass = item.change_amount > 0 ? 'text-danger' : (item.change_amount < 0 ? 'text-success' : 'text-muted');
                        const changeText = item.change_amount > 0 ? '+' + parseFloat(item.change_amount).toFixed(2) : parseFloat(item.change_amount).toFixed(2);
                        const createTime = item.create_time ? item.create_time : '';
                        const oldPrice = parseFloat(item.old_price || (parseFloat(item.price) - parseFloat(item.change_amount || 0)));
                        
                        html += `
                            <tr>
                                <td>${createTime}</td>
                                <td>¥${oldPrice.toFixed(2)}</td>
                                <td>¥${parseFloat(item.price).toFixed(2)}</td>
                                <td class="${changeClass}">${changeText}</td>
                                <td>${item.reason || '-'}</td>
                                <td>${item.remark || '-'}</td>
                                <td>${item.member_name || (item.member_id ? '管理员' + item.member_id : '系统')}</td>
                            </tr>
                        `;
                    });
                    $('#priceHistoryTable tbody').html(html);
                } else if (response[0] === 'success' && response[2] && Array.isArray(response[2])) {
                    // 处理非分页格式的数据
                    let html = '';
                    response[2].forEach(function(item) {
                        const changeClass = item.change_amount > 0 ? 'text-danger' : (item.change_amount < 0 ? 'text-success' : 'text-muted');
                        const changeText = item.change_amount > 0 ? '+' + parseFloat(item.change_amount).toFixed(2) : parseFloat(item.change_amount).toFixed(2);
                        const createTime = item.create_time ? item.create_time : '';
                        const oldPrice = parseFloat(item.old_price || (parseFloat(item.price) - parseFloat(item.change_amount || 0)));
                        
                        html += `
                            <tr>
                                <td>${createTime}</td>
                                <td>¥${oldPrice.toFixed(2)}</td>
                                <td>¥${parseFloat(item.price).toFixed(2)}</td>
                                <td class="${changeClass}">${changeText}</td>
                                <td>${item.reason || '-'}</td>
                                <td>${item.remark || '-'}</td>
                                <td>${item.member_name || (item.member_id ? '管理员' + item.member_id : '系统')}</td>
                            </tr>
                        `;
                    });
                    $('#priceHistoryTable tbody').html(html);
                } else {
                    // 没有数据时显示空状态
                    $('#priceHistoryTable tbody').html('<tr><td colspan="7" class="text-center text-muted">暂无价格变动记录</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                console.error('价格历史请求失败:', error);
                $('#priceHistoryTable tbody').html('<tr><td colspan="7" class="text-center text-danger">数据加载失败</td></tr>');
            }
        });
    }

// 加载价格趋势
function loadPriceTrend(productId, period = '30d') {
    // 先清空当前显示，避免显示上次查询的数据
    if (priceChart) {
        priceChart.destroy();
        priceChart = null;
    }
    
    // 显示加载状态
    $('#maxPrice').text('加载中...');
    $('#minPrice').text('加载中...');
    $('#avgPrice').text('加载中...');
    $('#changeCount').text('加载中...');
    
    const ctx = document.getElementById('priceChart');
    if (ctx) {
        const context = ctx.getContext('2d');
        context.clearRect(0, 0, ctx.width, ctx.height);
        context.fillStyle = '#f8f9fa';
        context.fillRect(0, 0, ctx.width, ctx.height);
        context.fillStyle = '#6c757d';
        context.font = '16px Arial';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText('加载中...', ctx.width / 2, ctx.height / 2);
    }
    
    $.ajax({
        url: '{:url("price/trend")}',
        type: 'POST',
        data: { product_id: productId, period: period },
        dataType: 'json',
        success: function(response) {
            console.log('价格趋势数据:', response); // 调试日志
            // OneBase返回格式：['success', '消息', data] 或 ['error', '消息']
            if (response[0] === 'success' && response[2] && Array.isArray(response[2]) && response[2].length > 0) {
                console.log('绘制图表数据:', response[2]); // 调试日志
                drawPriceChart(response[2]);
                updateModalPriceStats(response[2]);
            } else {
                console.warn('价格趋势数据为空或获取失败:', response);
                // 显示空状态 - 调用drawPriceChart处理空数据
                drawPriceChart(null);
            }
        },
        error: function(xhr, status, error) {
            console.error('价格趋势请求失败:', error);
            // 显示错误状态
            $('#maxPrice').text('--');
            $('#minPrice').text('--');
            $('#avgPrice').text('--');
            $('#changeCount').text('--');
            
            // 显示错误图表
            if (priceChart) {
                priceChart.destroy();
                priceChart = null;
            }
            
            const ctx = document.getElementById('priceChart');
            if (ctx) {
                const context = ctx.getContext('2d');
                context.clearRect(0, 0, ctx.width, ctx.height);
                context.fillStyle = '#f8f9fa';
                context.fillRect(0, 0, ctx.width, ctx.height);
                context.fillStyle = '#dc3545';
                context.font = '16px Arial';
                context.textAlign = 'center';
                context.textBaseline = 'middle';
                context.fillText('加载失败', ctx.width / 2, ctx.height / 2);
            }
        }
    });
}

// 加载快速价格选择
function loadQuickPriceSelect(productId) {
    $.ajax({
        url: '{:url("price/history")}',
        type: 'POST',
        data: { product_id: productId, limit: 5, quick_select: true }, // 添加快速选择标识
        dataType: 'json',
        success: function(response) {
            console.log('快速选择数据:', response); // 调试日志
            // OneBase返回格式：['success', '消息', data] 或 ['error', '消息']
            if (response[0] === 'success' && response[2] && response[2].data && Array.isArray(response[2].data)) {
                // 处理分页格式的数据
                const quickData = response[2].data;
                let html = '';
                quickData.forEach(function(item) {
                    // const createTime = item.create_time ? item.create_time : item.price_date;
                    html += `
                        <button class="btn btn-default btn-xs quick-price-btn" onclick="selectQuickPrice(${item.price})">
                            ¥${parseFloat(item.price).toFixed(2)}
                        </button>
                    `;
                });
                $('#quickPriceSelect').html(html);
            } else if (response[0] === 'success' && response[2] && Array.isArray(response[2])) {
                // 处理非分页格式的数据
                let html = '';
                response[2].forEach(function(item) {
                    // const createTime = item.create_time ? item.create_time : item.price_date;
                    html += `
                        <button class="btn btn-default btn-xs quick-price-btn" onclick="selectQuickPrice(${item.price})">
                            ¥${parseFloat(item.price).toFixed(2)}
                        </button>
                    `;
                });
                $('#quickPriceSelect').html(html);
            } else {
                // 没有数据时显示提示
                $('#quickPriceSelect').html('<span class="text-muted">暂无历史价格</span>');
            }
        },
        error: function(xhr, status, error) {
            console.error('快速选择请求失败:', error);
            $('#quickPriceSelect').html('<span class="text-danger">加载失败</span>');
        }
    });
}

// 选择快速价格
function selectQuickPrice(price) {
    $('#currentPrice').val(price);
}

// 绘制价格趋势图
function drawPriceChart(data) {
    console.log('开始绘制图表，数据:', data); // 调试日志
    
    // 先销毁现有图表
    if (priceChart) {
        priceChart.destroy();
        priceChart = null;
    }
    
    const ctx = document.getElementById('priceChart');
    if (!ctx) {
        console.error('找不到图表canvas元素');
        return;
    }
    
    // 如果数据为空或无效，显示空状态
    if (!data || !Array.isArray(data) || data.length === 0) {
        console.warn('图表数据为空或无效，显示空状态');
        
        // 清空画布
        const context = ctx.getContext('2d');
        context.clearRect(0, 0, ctx.width, ctx.height);
        
        // 绘制空状态背景
        context.fillStyle = '#f8f9fa';
        context.fillRect(0, 0, ctx.width, ctx.height);
        
        // 绘制空状态文字
        context.fillStyle = '#6c757d';
        context.font = '16px Arial';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText('暂无数据', ctx.width / 2, ctx.height / 2);
        
        // 清空统计信息
        $('#maxPrice').text('--');
        $('#minPrice').text('--');
        $('#avgPrice').text('--');
        $('#changeCount').text('--');
        
        return;
    }
    
    try {
        priceChart = new Chart(ctx.getContext('2d'), {
            type: 'line',
            data: {
                labels: data.map(item => item.date),
                datasets: [{
                    label: '价格趋势',
                    data: data.map(item => parseFloat(item.price)),
                    borderColor: 'rgb(75, 192, 192)',
                    backgroundColor: 'rgba(75, 192, 192, 0.1)',
                    tension: 0.1,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '价格趋势分析'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        ticks: {
                            callback: function(value) {
                                return '¥' + value;
                            }
                        }
                    }
                }
            }
        });
        console.log('图表绘制成功');
    } catch (error) {
        console.error('图表绘制失败:', error);
        
        // 绘制错误状态
        const context = ctx.getContext('2d');
        context.clearRect(0, 0, ctx.width, ctx.height);
        context.fillStyle = '#f8f9fa';
        context.fillRect(0, 0, ctx.width, ctx.height);
        context.fillStyle = '#dc3545';
        context.font = '16px Arial';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText('图表加载失败', ctx.width / 2, ctx.height / 2);
    }
}

// 更新价格统计信息
function updateModalPriceStats(data) {
    console.log('价格统计数据:', data); // 调试日志
    
    let priceData = [];
    
    // 处理不同的数据格式
    if (Array.isArray(data)) {
        // 直接是数组格式
        priceData = data;
    } else if (data && data.data && Array.isArray(data.data)) {
        // 分页格式的数据
        priceData = data.data;
    } else if (data && Array.isArray(data)) {
        // 已经是数组
        priceData = data;
    }
    
    if (priceData.length === 0) {
        // 没有数据时显示默认值
        $('#maxPrice').text('--');
        $('#minPrice').text('--');
        $('#avgPrice').text('--');
        $('#changeCount').text('0');
        return;
    }
    
    // 提取价格数组
    const prices = priceData.map(item => parseFloat(item.price) || 0);
    
    // 计算统计信息
    const maxPrice = Math.max(...prices);
    const minPrice = Math.min(...prices);
    const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
    const changeCount = priceData.length;
    
    // 更新显示
    $('#maxPrice').text('¥' + maxPrice.toFixed(2));
    $('#minPrice').text('¥' + minPrice.toFixed(2));
    $('#avgPrice').text('¥' + avgPrice.toFixed(2));
    $('#changeCount').text(changeCount);
}

// 切换时间周期
function changePeriod(period) {
    loadPriceTrend(currentProductId, period);
    
    // 更新按钮状态
    $('.panel-heading .btn').removeClass('btn-primary').addClass('btn-default');
    $(`button[onclick="changePeriod('${period}')"]`).removeClass('btn-default').addClass('btn-primary');
}

// 保存价格变动
function savePriceChange() {
    const productId = currentProductId;
    const price = $('#currentPrice').val();
    const date = $('#priceDate').val();
    const reason = $('#changeReason').val();
    const remark = $('#priceRemark').val();
    const onlyHistory = $('#onlyHistory').is(':checked');
    
    if (!price || !date) {
        toast.warning('请填写完整的价格信息');
        return;
    }
    
    $.ajax({
        url: '{:url("price/change")}',
        type: 'POST',
        data: {
            product_id: productId,
            price: price,
            price_date: date,
            reason: reason,
            remark: remark,
            only_history: onlyHistory ? 1 : 0
        },
        dataType: 'json',
        success: function(response) {
            // OneBase返回格式：['success', '消息'] 或 ['error', '消息']
            if (response[0] === 'success') {
                toast.success(response[1] || '价格保存成功');
                // 重新加载数据
                loadPriceHistory(productId);
                loadPriceTrend(productId);
                loadQuickPriceSelect(productId);
                // 清空表单
                $('#priceRemark').val('');
                $('#changeReason').val('');
                $('#onlyHistory').prop('checked', true);
            } else {
                toast.error(response[1] || '保存失败');
            }
        },
        error: function() {
            toast.error('网络错误，请重试');
        }
    });
}

// 批量调价
function batchPriceAdjust() {
    if (selectedProducts.length === 0) {
        toast.warning('请先选择要调价的产品');
        return;
    }
    
    // 使用layer弹窗
    layer.open({
        type: 2,
        title: '批量价格调整',
        shadeClose: true,
        shade: 0.8,
        area: ['900px', '600px'],
        content: '{:url("price/batchAdjust")}?product_ids=' + selectedProducts.map(p => p.id).join(','),
        end: function() {
            // 弹窗关闭后刷新页面
            location.reload();
        }
    });
}



// 价格预警
function batchPriceAlert() {
    if (selectedProducts.length === 0) {
        toast.warning('请先选择要设置预警的产品');
        return;
    }
    
    // 使用layer弹窗
    layer.open({
        type: 2,
        title: '价格预警设置',
        shadeClose: true,
        shade: 0.8,
        area: ['600px', '500px'],
        content: '{:url("price/saveAlert")}?product_ids=' + selectedProducts.map(p => p.id).join(','),
        end: function() {
            // 弹窗关闭后可选择性刷新
            console.log('价格预警设置完成');
        }
    });
}



// 导出价格历史
function exportPriceHistory() {
    window.open('{:url("price/exportHistory")}?product_id=' + currentProductId);
}

//导出功能
$(".export").click(function(){
    
    window.location.href = searchFormUrl($(".export"));
});
</script>
